//
//  GWTool.m
//  GiganticWhale
//
//  Created by 裴烨烽 on 16/2/8.
//  Copyright © 2016年 GiganticWhale. All rights reserved.
//

#import "GWTool.h"
#import <CommonCrypto/CommonDigest.h>
#import <sys/xattr.h>
#import <objc/runtime.h>

CGFloat LCFloat (CGFloat floatValue) {
    return LCFloatWithPadding(floatValue, 0.0f);
}


CGFloat LCFloatWithPadding(CGFloat floatValue, CGFloat padding) {
    CGFloat currentScreenWidth = kScreenBounds.size.width - padding;
    CGFloat standardScreenWidth = 375.0f - padding;
    return floorl(floatValue / standardScreenWidth * currentScreenWidth) ;
}

@implementation GWTool


+(NSString *)replaceSpace:(NSString *)string{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}

// 获取当前时间戳
+ (NSString *)getCurrentTimeInterval{
    return [NSString stringWithFormat:@"%ld", (long)[[NSDate  date] timeIntervalSince1970]];
}


#pragma mark - check String is Empty
+ (BOOL)isEmpty:(NSString *)string
{
    if (![string isKindOfClass:[NSString class]])
        string = [string description];
    if (string == nil || string == NULL)
        return YES;
    if ([string isKindOfClass:[NSNull class]])
        return YES;
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0)
        return YES;
    if ([string isEqualToString:@"(null)"])
        return YES;
    if ([string isEqualToString:@"(null)(null)"])
        return YES;
    if ([string isEqualToString:@"<null>"])
        return YES;
    
    // return Default
    return NO;
}


#pragma mark - 手机号码验证
+ (BOOL)validateMobile:(NSString *)mobile {
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^1((3|5|7|8)\\d)\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

+(BOOL)validateUserName:(NSString *)userName{
    // 不能以数字开头
    NSString *userNameRegex = @"^[a-zA-Z][a-zA-Z0-9_]{4,15}$";
    NSPredicate *userNameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    return [userNameTest evaluateWithObject:userName];
}

#pragma mark 密码正则表达式
+(BOOL)validatePassword:(NSString *)password{
    // 密码大小写数字，不能是符号
    NSString *passwordRegex = @"^[A-Za-z0-9]+$";
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passwordRegex];
    return [passwordTest evaluateWithObject:password];
}

#pragma mark - 验证码验证
+ (BOOL)isPureNumandCharacters:(NSString *)string {
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0) {
        return NO;
    }
    return YES;
}


#pragma mark - 键盘抖动
+(void)lockAnimationForView:(UIView*)view {
    CALayer *lbl = [view layer];
    CGPoint posLbl = [lbl position];
    CGPoint y = CGPointMake(posLbl.x-10, posLbl.y);
    CGPoint x = CGPointMake(posLbl.x+10, posLbl.y);
    CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction
                                  functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    [animation setAutoreverses:YES];
    [animation setDuration:0.08];
    [animation setRepeatCount:3];
    [lbl addAnimation:animation forKey:nil];
}

+ (void)animationWithCollectionWithButton:(UIImageView *)collectionButton collection:(BOOL)isCollection callback:(void(^)())callbackBlock{
    if (isCollection){
        collectionButton.image = [UIImage imageNamed:@"btn_center_sugges_selected"];
    } else {
        collectionButton.image = [UIImage imageNamed:@"btn_center_sugges_unSelected"];
    }
    CAKeyframeAnimation *collectionOfAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    collectionOfAnimation.values = @[@(0.1),@(1.0),@(1.5)];
    collectionOfAnimation.keyTimes = @[@(0.0),@(0.5),@(0.8),@(1.0)];
    collectionOfAnimation.calculationMode = kCAAnimationLinear;
    
    isCollection = !isCollection;
    [collectionButton.layer addAnimation:collectionOfAnimation forKey:@"SHOW"];
    callbackBlock();
}



#pragma mark - 拉伸图片
+ (UIImage *)stretchImageWithName:(NSString *)name {
    UIImage *image = [UIImage imageNamed:name];
    return [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
}

#pragma mark - UITabelViewCell_Clean
+(UIImage *)addBackgroundImageViewWithCellWithDataArray:(NSArray *)dataArray indexPath:(NSIndexPath *)indexPath{
    NSArray *sectionOfArray = [dataArray objectAtIndex:indexPath.section];
    NSString *backgroundImageName = nil;
    if (sectionOfArray.count == 1){
        backgroundImageName = @"login_frame_single";
    } else if (indexPath.row == 0){
        backgroundImageName = @"login_frame_top";
    } else if (indexPath.row == sectionOfArray.count - 1){
        backgroundImageName = @"login_frame_bottom";
    }
    UIImage *cellBackgroundImage = [self stretchImageWithName:backgroundImageName];
    return cellBackgroundImage;
}

+(UIImage *)addBackgroundImageViewWithRefundCellWithDataArray:(NSArray *)dataArray indexPath:(NSIndexPath *)indexPath{
    NSArray *sectionOfArray = [dataArray objectAtIndex:indexPath.section];
    NSString *backgroundImageName = nil;
    if (sectionOfArray.count == 1){
        backgroundImageName = @"login_frame_single";
    } else if (indexPath.row == 0){
        backgroundImageName = @"circle_top";
    } else if (indexPath.row == sectionOfArray.count - 1){
        backgroundImageName = @"circle_bottom";
    } else {
        backgroundImageName = @"circle_mid";
    }
    UIImage *cellBackgroundImage = [self stretchImageWithName:backgroundImageName];
    return cellBackgroundImage;
}

+(void)animationClickShowWithView:(UIButton *)button block:(void(^)())block{
    CAKeyframeAnimation *collectionOfAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    collectionOfAnimation.values = @[@(0.1),@(1.0),@(1.5)];
    collectionOfAnimation.keyTimes = @[@(0.0),@(0.5),@(0.8),@(1.0)];
    collectionOfAnimation.calculationMode = kCAAnimationLinear;
    [button.layer addAnimation:collectionOfAnimation forKey:@"SHOW"];
    if (block){
        block();
    }
}


#pragma mark 拨打电话客服
+ (void)callCustomerServer:(UIView *)view phoneNumber:(NSString *)phoneNumber{
  
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
}

#pragma mark 打开网址
+(void)openURLWithURL:(NSString *)url{
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}

#pragma mark 获取目标时间
+ (NSTimeInterval)getTargetDateTimeWithTimeInterval:(NSTimeInterval)time{
    NSDate *nowDate = [NSDate date];                                // 当前时间
    NSDate *targetDate = [nowDate dateByAddingTimeInterval:time];   // 目标时间
    NSTimeInterval targetDateWithTimeInterval = [targetDate timeIntervalSince1970];
    return targetDateWithTimeInterval;
}


#pragma mark 计算倒计时时间
+ (NSString *)getCountdownWithTargetDate:(NSTimeInterval)targetDateWithTimeInterval{
    NSDate *nowDate = [NSDate date];
    NSDate *targetDate = [NSDate dateWithTimeIntervalSince1970:targetDateWithTimeInterval];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components: (NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear )
                                                        fromDate:nowDate
                                                          toDate:targetDate
                                                         options:0];
    
    NSString * miniString = [NSString stringWithFormat:@"%ld",(long)[components minute]];
    NSString * secString = [NSString stringWithFormat:@"%ld",(long)[components second]];
    
    return [NSString stringWithFormat:@"%@分%@秒后订单失效",miniString,secString];
}

#pragma mark 统计文字
+ (NSUInteger)calculateCharacterLengthForAres:(NSString *)str {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < [str length]; i++) {
        asciiLength = str.length;
    }
    return asciiLength;
}


#pragma mark rangeLabel
+ (NSMutableAttributedString *)rangeLabelWithContent:(NSString *)content hltContentArr:(NSArray *)hltContentArr hltColor:(UIColor *)hltColor normolColor:(UIColor *)normolColor{
    NSMutableArray *hltRangeArr = [NSMutableArray array];
    for (int i = 0;i < hltContentArr.count;i++){
        NSRange range = [content rangeOfString:[hltContentArr objectAtIndex:i]];
        if (range.location != NSNotFound){
            NSValue *rectValue = [NSValue valueWithBytes:&range  objCType:@encode(NSRange)];
            if (rectValue !=nil){
                [hltRangeArr addObject:rectValue];
            }
        }
    }
    NSMutableAttributedString *mutableAttributedString;
    if (content.length){
        mutableAttributedString = [[NSMutableAttributedString alloc]initWithString:content];
    }
    NSMutableArray *rangeTempMutableArr = [NSMutableArray array];
    NSRange zeroRange;
    zeroRange.length = 0;
    zeroRange.location = 0;
    NSValue *zeroRangeValue = [NSValue valueWithBytes:&zeroRange  objCType:@encode(NSRange)];
    [rangeTempMutableArr addObject:zeroRangeValue];
    
    for (int i = 0 ; i < hltRangeArr.count;i++){
        NSRange hltRange = [[hltRangeArr objectAtIndex:i] rangeValue];
        NSRange lastHltRange = [[rangeTempMutableArr lastObject] rangeValue];
        
        // normolRange
        NSRange normolRange;
        normolRange.location = lastHltRange.length + lastHltRange.location;
        normolRange.length = hltRange.location - normolRange.location;
        
        [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:hltColor range:hltRange];
        [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:normolColor range:normolRange];
        
        NSValue *rectValue = [NSValue valueWithBytes:&hltRange  objCType:@encode(NSRange)];
        [rangeTempMutableArr addObject:rectValue];
    }
    NSRange lastHltRange = [[rangeTempMutableArr lastObject] rangeValue];
    NSRange lastNormolRange;
    lastNormolRange.location = lastHltRange.length + lastHltRange.location;
    lastNormolRange.length = content.length - lastNormolRange.location;
    [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:normolColor range:lastNormolRange];
    return  mutableAttributedString;
}

+ (NSMutableAttributedString *)rangeLabelWithContent:(NSString *)content hltContentArr:(NSArray *)hltContentArr hltColor:(UIColor *)hltColor hltFont:(UIFont *)hltFont normolColor:(UIColor *)normolColor normalFont:(UIFont *)normalFont{
    NSMutableArray *hltRangeArr = [NSMutableArray array];
    for (int i = 0;i < hltContentArr.count;i++){
        NSRange range = [content rangeOfString:[hltContentArr objectAtIndex:i]];
        if (range.location != NSNotFound){
            NSValue *rectValue = [NSValue valueWithBytes:&range  objCType:@encode(NSRange)];
            if (rectValue !=nil){
                [hltRangeArr addObject:rectValue];
            }
        }
    }
    NSMutableAttributedString *mutableAttributedString;
    if (content.length){
        mutableAttributedString = [[NSMutableAttributedString alloc]initWithString:content];
    }
    NSMutableArray *rangeTempMutableArr = [NSMutableArray array];
    NSRange zeroRange;
    zeroRange.length = 0;
    zeroRange.location = 0;
    NSValue *zeroRangeValue = [NSValue valueWithBytes:&zeroRange  objCType:@encode(NSRange)];
    [rangeTempMutableArr addObject:zeroRangeValue];
    
    for (int i = 0 ; i < hltRangeArr.count;i++){
        NSRange hltRange = [[hltRangeArr objectAtIndex:i] rangeValue];
        NSRange lastHltRange = [[rangeTempMutableArr lastObject] rangeValue];
        
        // normolRange
        NSRange normolRange;
        normolRange.location = lastHltRange.length + lastHltRange.location;
        normolRange.length = hltRange.location - normolRange.location;
        
        [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:hltColor range:hltRange];
        [mutableAttributedString addAttribute:NSFontAttributeName value:hltFont range:hltRange];
        
        [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:normolColor range:normolRange];
        [mutableAttributedString addAttribute:NSFontAttributeName value:normalFont range:normolRange];
        
        NSValue *rectValue = [NSValue valueWithBytes:&hltRange  objCType:@encode(NSRange)];
        [rangeTempMutableArr addObject:rectValue];
    }
    NSRange lastHltRange = [[rangeTempMutableArr lastObject] rangeValue];
    NSRange lastNormolRange;
    lastNormolRange.location = lastHltRange.length + lastHltRange.location;
    lastNormolRange.length = content.length - lastNormolRange.location;
    [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:normolColor range:lastNormolRange];
    [mutableAttributedString addAttribute:NSFontAttributeName value:normalFont range:lastNormolRange];
    return  mutableAttributedString;
}




#pragma mark -UserDefault
// 存入
+(void)userDefaulteWithKey:(NSString *)key Obj:(NSString *)objString{
    [USERDEFAULTS synchronize];
    [USERDEFAULTS setObject:objString forKey:key];
}

// 获取
+(NSString *)userDefaultGetWithKey:(NSString *)key{
    NSString *lastDate = [USERDEFAULTS objectForKey:key];
    [USERDEFAULTS synchronize];
    return lastDate;
}
//删除
+(void)userDefaultDelegtaeWithKey:(NSString *)key{
    [USERDEFAULTS removeObjectForKey:key];
    [USERDEFAULTS synchronize];
}

#pragma mark - 号码裁剪
+(NSString *)numberCutting:(NSString *)number {
    NSRange range  = NSMakeRange (0,3);
    //    NSRange range1 = NSMakeRange(3,4);
    NSRange range2 = NSMakeRange(7,4);
    
    number=[NSString stringWithFormat:@"%@%@%@",[number substringWithRange:range],@"****",[number substringWithRange:range2]];
    return number;
}

#pragma mark - 号码裁剪
+(NSString *)numberCuttingWithBankCard:(NSString *)number {
    NSInteger numberLength = number.length;
    NSRange range  = NSMakeRange (0,4);
    NSRange range2 = NSMakeRange(numberLength - 4,4);
    
    
    NSString *rangeString = @"";
    for (int i = 0 ; i < numberLength - 8;i++){
        rangeString = [rangeString stringByAppendingString:@"*"];
    }
    number=[NSString stringWithFormat:@"%@%@%@",[number substringWithRange:range],rangeString,[number substringWithRange:range2]];
    return number;
}

+(NSString *)appName{
    NSDictionary *dic = [[NSBundle mainBundle] infoDictionary];//获取info－plist
    NSString *appName = [dic objectForKey:@"CFBundleDisplayName"];//获取Bundle identifier
    return appName;
}

+(NSString *)appVersion{
    NSDictionary *dic = [[NSBundle mainBundle] infoDictionary];//获取info－plist
    NSString *appVersion = [dic valueForKey:@"CFBundleShortVersionString"];
    return appVersion;
}

+(void)copyWithString:(NSString *)text callback:(void (^)())callBack{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = text;
    callBack();
}

+(CGFloat)smartFloat:(CGFloat)floatValue{
    CGFloat currentScreenWidth = kScreenBounds.size.width;
    CGFloat standardScreenWidth = 375.0f;
    return floatValue / standardScreenWidth * currentScreenWidth ;
}

//
+ (UIImage*) createImageWithColor: (UIColor*) color frame:(CGRect)rect {
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}


+(void)clickZanWithView:(UIView *)button block:(void(^)())block{
    CAKeyframeAnimation *collectionOfAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    collectionOfAnimation.values = @[@(0.1),@(1.0),@(1.5)];
    collectionOfAnimation.keyTimes = @[@(0.0),@(0.5),@(0.8),@(1.0)];
    collectionOfAnimation.calculationMode = kCAAnimationLinear;
    [button.layer addAnimation:collectionOfAnimation forKey:@"SHOW"];
    if (block){
        block();
    }
}

+ (UIImage *)imageByComposingImage:(UIImage *)image withMaskImage:(UIImage *)maskImage {
    CGImageRef maskImageRef = maskImage.CGImage;
    CGImageRef maskRef = CGImageMaskCreate(CGImageGetWidth(maskImageRef),
                                           CGImageGetHeight(maskImageRef),
                                           CGImageGetBitsPerComponent(maskImageRef),
                                           CGImageGetBitsPerPixel(maskImageRef),
                                           CGImageGetBytesPerRow(maskImageRef),
                                           CGImageGetDataProvider(maskImageRef), NULL, false);
    
    CGImageRef newImageRef = CGImageCreateWithMask(image.CGImage, maskRef);
    CGImageRelease(maskRef);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    CGImageRelease(newImageRef);
    
    return newImage;
}

+(CGSize)makeSizeWithLabel:(UILabel *)label{
    CGSize contentOfSize = [label.text sizeWithCalcFont:label.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, [NSString contentofHeight:label.font])];
    return CGSizeMake(contentOfSize.width, [NSString contentofHeight:label.font]);
}

#pragma mark 切圆角
- (void)cutRoundView:(UIImageView *)imageView {
    CGFloat corner = imageView.frame.size.width / 2;
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(corner, corner)];
    shapeLayer.path = path.CGPath;
    imageView.layer.mask = shapeLayer;
}


+ (UIWindow *)lastWindow {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in [windows reverseObjectEnumerator]) {
        
        if ([window isKindOfClass:[UIWindow class]] &&
            CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds))
            
            return window;
    }
    
    return [UIApplication sharedApplication].keyWindow;
}


+(void)setTransferSingleAsset:(UIImage *)transferSingleAsset imgView:(GWImageView*)imgView convertView:(UIView *)convertView{
    CGImageRef posterImage = transferSingleAsset.CGImage;
    // 1. 获取当前图片高度
    size_t posterImageHeight = CGImageGetHeight(posterImage);
    CGFloat scale = posterImageHeight / convertView.size_height;
    imgView.image = [UIImage imageWithCGImage:posterImage scale:scale orientation:UIImageOrientationUp];
    
    // 基本尺寸参数
    CGSize boundsSize = convertView.bounds.size;
    CGFloat boundsWidth = boundsSize.width;
    CGFloat boundsHeight = boundsSize.height;
    
    CGSize imageSize = imgView.image.size;
    CGFloat imageWidth = imageSize.width;
    CGFloat imageHeight = imageSize.height;
    
    if (imageWidth == 0 || imageHeight == 0){
        return;
    }
    CGRect imageFrame = CGRectMake(0, (boundsHeight - boundsWidth) / 2., boundsWidth, imageHeight * boundsWidth / imageWidth);
    
    if (imageHeight > imageWidth){          // 图片高度大于图片宽度
        if (imageFrame.size.height < boundsHeight) {
            imageFrame.origin.y = floorf((boundsHeight - imageFrame.size.height) / 2.0);
        } else {
            imageFrame.origin.y = 0;
        }
    } else {                                // 图片宽度大于高度
        if (imageFrame.size.width < boundsWidth){
            imageFrame.origin.x = 0;
            imageFrame.size.width = (boundsHeight * 1.00 / imageFrame.size.height) *imageFrame.size.width;
            imageFrame.size.height = boundsHeight;
        } else {
            imageFrame.size.width = boundsWidth;
            imageFrame.size.height = (boundsWidth / imageFrame.size.width) * imageFrame.size.height;
            imageFrame.origin.x = - floorf((imageFrame.size.width - boundsWidth) / 2.0);
            imageFrame.origin.y = - floorf((imageFrame.size.height - boundsHeight) / 2.);
            
            if (imageFrame.size.height < boundsHeight){
                imageFrame.size.height = boundsHeight;
                imageFrame.size.width = (boundsHeight / imageFrame.size.height) * boundsWidth;
                imageFrame.origin.x = - floorf((imageFrame.size.width - boundsWidth) / 2.0);
                imageFrame.origin.y = - floorf((imageFrame.size.height - boundsHeight) / 2.);
            }
            
        }
    }
    imgView.frame = imageFrame;
}


// 自动计算宽度
+(CGSize)autoAdjustFontSizeWithLabel:(UILabel *)label{
    CGSize size = [label.text sizeWithCalcFont:label.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, [NSString contentofHeight:label.font])];
    return size;
}
@end
